package demo;

public class Demo13 {
    public static void main(String[] args) {
        /*
         * 将7进制解析为整数
         */
        String str = "-123";
        // 将字符串s按照7进制解析为整数
        int num = Integer.parseInt(str, 7);
        System.out.println(num);
        num = parseInt(str, 7);
        System.out.println(num);
    }
    public static int parseInt(String str, int radix){
        //negative 负数, 负号
        boolean negative = str.charAt(0)=='-'; //第一个字符是'-'就是负数
        int end = negative ? 1 : 0;
        int weight = 1;
        int sum = 0;
        for(int i=str.length()-1; i>=end; i--){
            char c = str.charAt(i);
            int n = c-'0';
            if (n<0||n>=radix){
                throw new NumberFormatException("解析错误:"+c);
            }
            sum += (str.charAt(i)-'0') * weight;
            weight *= radix;
        }
        return negative ? -sum : sum;
    }
}




